import MySQLdb
import logging
import os, sys


def getWrapperWithCursor(cursor):
  db = DBWrapper();
  db.setCursor(cursor);
  return db;

class DBWrapper():
  def __init__(self):
    self.db = None
    self.host = None
    self.user = None
    self.password = None
    self.conn = None
    self.cursor = None

  def _execute(self, cmd):
    try:
      print cmd
      self.cursor.execute(cmd)
      return 0
    except Exception, e:
      logging.info('Error execute database command %s' % (str(e)))
      print str(e)
      return -1

  def setParam(self, host, user, password, db):
    self.db = db
    self.host = host
    self.user = user
    self.password = password

  def connectMySQL(self):
    if self.db is not None:
      try:
        self.conn = MySQLdb.connect(self.host, self.user, \
                                 self.password, self.db)
      except MySQLdb.Error, e:
        loggin.info("Error %d: %s" % (e.args[0], e.args[1]))
        sys.exit(1)
      self.cursor = self.conn.cursor()

  def setCursor(self, cursor):
    self.cursor = cursor;

  def disconnect(self):
    if self.cursor is not None:
       self.cursor.close()
    if self.conn is not None:
       self.conn.close()

  def checkUseDB(self, dbName):
    cmd = "USE %s"% (dbName)
    if (self._execute(cmd) >= 0):
      return True
    else:
      return False

  def checkTable(self, tableName):
    cmd = "SELECT 1 FROM %s"% (tableName)
    if (self._execute(cmd) >= 0):
      return True
    else:
      return False

  def create(self, tableName, schema):
    cmd = "CREATE TABLE %s (%s)" % (tableName, schema)
    self._execute(cmd)

  def insert(self, tableName, names, vals):
    cmd = "INSERT INTO %s %s VALUES %s" % (tableName, names, vals)
    self._execute(cmd)

  def insertOne(self, tableName, name1, val1):
    cmd = "INSERT INTO %s (%s) VALUES %s" % (tableName, name1, val1)
    self._execute(cmd)

  def insertPair(self, tableName, name1, name2, val1, val2):
    cmd = "INSERT INTO %s (%s, %s) VALUES (%s, %s)" \
        % (tableName, name1, name2, val1, val2)
    self._execute(cmd)

  def insertTriple(self, tableName,
                   name1, name2, name3,
                   val1, val2, val3):
    cmd = "INSERT INTO %s (%s, %s, %s) VALUES (%s, %s, %s)" \
        % (tableName, \
           name1, name2, name3, \
           val1, val2, val3)
    self._execute(cmd)

  def selectNoCondition(self, tableName, expr):
    cmd = "SELECT %s FROM %s" % (expr, tableName)
    if (self._execute(cmd) == 0):
      rows = self.cursor.fetchall()
      return rows;
    else:
      return [];

  def select(self, tableName, expr, condition):
    cmd = "SELECT %s FROM %s WHERE %s" % (expr, tableName, condition)
    if (self._execute(cmd) == 0):
      rows = self.cursor.fetchall()
      return rows;
    else:
      return [];

  def selectMany(self, tableName, expr, condition, size):
    cmd = "SELECT %s FROM %s WHERE %s" % (expr, tableName, where)
    if (self._execute(cmd) == 0):
      rows = self.cursor.fetchmany(size)
      return rows;
    else:
      return [];

  def selectSequence(self, tableName, x, y, start, end):
    expr = "%s, %s" % (x, y)
    condition =  "(%s >= %s) and (%s <= %s)" % (x, start, x, end)
    return self.select(tableName, expr, condition)

  def selectSeqCond(self, tableName, x, y, start, end, cond):
    expr = "%s, %s" % (x, y)
    if (cond is not None):
      condition =  "(%s >= %s) and (%s <= %s) and %s" % \
         (x, start, x, end, cond)
    else:
      condition =  "(%s >= %s) and (%s <= %s)" % \
         (x, start, x, end)
    print expr, condition
    return self.select(tableName, expr, condition)

  def selectDistinct(self, tableName, name):
    expr = "distinct %s" % (name)
    rows = self.selectNoCondition(tableName, expr)
    res = []
    for row in rows:
      res.append(row[0])
    return res

  def getMore(self, size):
    try:
      rows = self.cursor.fetchmany(size);
    except Exception, e:
      rows = []
    return rows;

  def existItem(self, tableName, name, vals):
    cmd = "SELECT 1 FROM %s WHERE %s=%s" % (tableName, name, vals)
    try:
      self.cursor.execute(cmd)
      res = self.cursor.fetchall()
      if len(res) > 0:
        return True
      else:
        return False
    except Exception, e:
      return False

  def existItemPred(self, tableName, predicate):
    cmd = "SELECT 1 FROM %s WHERE %s" % (tableName, predicate)
    try:
      self.cursor.execute(cmd)
      res = self.cursor.fetchall()
      if len(res) > 0:
        return True
      else:
        return False
    except Exception, e:
      return False
